<?php

namespace Lib\Controller;

use Lib\View\View,
    Lib\Request,
    Lib\Util\Inflector,
    Lib\Util\Util;

class Controller {

    public  $autoRender = true;
    public  $layout     = 'public';
    public  $config;

    private $request;
    private $viewVars = array();
    private $rendered = false;

    private $modelMap = array();

    public function __construct(Request $request) {
        $this->request = $request;
        $this->config  = json_decode(file_get_contents(DIR_CONFIG . DS . 'application.json'));
    }

    public function display() {
        header('Content-Type:text/html;charset=' . $this->config->encoding);
        echo Util::minify($this->render());
    }

    public function render($view = null) {
        if ($this->rendered) return;

        if (! $view) {
            $view = $this->request->action;
        }
        
        $this->rendered = true;
        View::setController($this);
        return View::render($this->request->controller . DS . $view, $this->layout, $this->viewVars);
    }

    public function setRequest($request) {
        $this->request = $request;
    }

    public function set($name, $value) {
        $this->viewVars[$name] = $value;
    }

    public function __get($name) {
        switch($name) {
            case 'name':
                return end(explode("\\", get_class($this)));

            case 'action':
                return $this->request->action;

            default:
                return $this->$name;
        }
    }

    public function loadModel($modelName) {
        if (empty($this->modelMap[$modelName])) {
            $className = "Model\\{$modelName}";
            $Model = new $className;
            $this->modelMap[$modelName] = $Model;
        }

        $this->$modelName = $this->modelMap[$modelName];

        return $this->modelMap[$modelName];
    }

    public function redirect($url) {
        if (!preg_match('/^\//', $url)) {
            $url = "/" . Inflector::underscore($this->name) . "/" . $url;
        }

        header("Location: $url");
        exit;
    }
}